#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db import models
from django.core.validators import MaxValueValidator
import os
import sys
import django
from web.util.datetime_util import DatetimeUtil
from web.constants.datetime_format import DatetimeFormat

sys.path.append(r"web")
sys.path.append(r"algorithm")
sys.path.append(r"cta")

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adam3.settings')
django.setup()


class Quant2CommodityFutureTransactionRecord(models.Model):
    """
    量化2--期货交易记录
    """

    # def __init__(self) -> None:
    #     super().__init__()

    # 主键
    id_ = models.AutoField(primary_key=True)

    # 账号名称
    account_name = models.CharField(max_length=32, db_index=True, null=True, blank=True)

    # 期货代码
    code = models.CharField(max_length=32, db_index=True, null=True, blank=True)

    # 买入日期
    buy_date = models.DateField(null=True, db_index=True, blank=True)

    # 买入价格
    buy_price = models.DecimalField(max_digits=32, decimal_places=16, null=True, blank=True)

    # 买入手数
    buy_lot = models.IntegerField(validators=[MaxValueValidator(2147483647)], null=True, blank=True)

    # 卖出日期
    sell_date = models.DateField(null=True, db_index=True, blank=True)

    # 卖出价格
    sell_price = models.DecimalField(max_digits=32, decimal_places=16, null=True, blank=True)

    # 卖出手数
    sell_lot = models.IntegerField(validators=[MaxValueValidator(2147483647)], null=True, blank=True)

    # 交易方向。1表示做多；-1表示做空
    direction = models.IntegerField(validators=[MaxValueValidator(2147483647)], null=True, blank=True)

    # 盈亏额（除以保证金，乘以交易乘数之后的）
    profit_and_loss = models.DecimalField(max_digits=32, decimal_places=16, null=True, blank=True)

    # 盈亏率（除以保证金，乘以交易乘数之后的）。单位%
    profit_and_loss_rate = models.DecimalField(max_digits=32, decimal_places=16, null=True, blank=True)

    # 开仓手续费
    open_commission = models.DecimalField(max_digits=32, decimal_places=16, null=True, blank=True)

    # 平仓手续费
    close_commission = models.DecimalField(max_digits=32, decimal_places=16, null=True, blank=True)

    # K线运行形态。1表示趋势形态，2表示震荡形态
    k_line_movement_pattern = models.IntegerField(validators=[MaxValueValidator(2147483647)], null=True, blank=True)

    # 平仓原因。1表示平仓非主力合约，2表示止损平仓，3表示普通平仓，4表示牛熊线减仓
    close_position_reason = models.IntegerField(validators=[MaxValueValidator(2147483647)], null=True, blank=True)

    def to_dict(self):
        """
        将对象转换为dict类型
        """

        return {
            'id': self.id,
            'robotName': self.robot_name,
            'code': self.code,
            'buyDate': DatetimeUtil.datetime_to_str(self.buy_date,
                                                    DatetimeFormat.Date_Format_With_Line) if self.buy_date != None else None,
            'buyPrice': float(self.buy_price) if self.buy_price != None else None,
            'buyLot': float(self.buy_lot) if self.buy_lot != None else None,
            'sellDate': DatetimeUtil.datetime_to_str(self.sell_date,
                                                     DatetimeFormat.Date_Format_With_Line) if self.sell_date != None else None,
            'sellPrice': float(self.sell_price) if self.sell_price != None else None,
            'sellLot': float(self.sell_lot) if self.sell_lot != None else None,
            'direction': self.direction,
            'profitAndLoss': float(self.profit_and_loss) if self.profit_and_loss != None else None,
            'profitAndLossRate': float(self.profit_and_loss_rate) if self.profit_and_loss_rate != None else None,
            'openCommission': float(self.open_commission) if self.open_commission != None else None,
            'closeCommission': float(self.close_commission) if self.close_commission != None else None
        }

    class Meta:
        managed = True
        db_table = 'quant2_c_f_transact_record'
        verbose_name = '量化2--期货交易记录'
        verbose_name_plural = verbose_name
        # 单列索引
        # indexes = [
        #     models.Index(fields=['code']),
        #     models.Index(fields=['k_line_period_type']),
        #     models.Index(fields=['begin_time']),
        #     models.Index(fields=['end_time']),
        #     models.Index(fields=['name']),
        # ]
        # 联合索引
        # index_together = [('code', 'buy_date', 'sell_date')]
